package com.zheng.oss.web.service;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.zheng.oss.web.entity.UEditorPut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.InputStream;

/**
 * Created by IntelliJ IDEA.
 * User: xinqi
 * Date: 2017/11/18
 * Time: 11:42
 */
@Service
public class QiniuOssService {
    private static Logger _log = LoggerFactory.getLogger(QiniuOssService.class);
    private static final String accessKey = "PiP1eibKgTTD2OuaTp5IX7kTFy5gVXdFLJP5Z3T9";
    private static final String secretKey = "0aSa-szBolNavHPwLACt6zD93N7jTYagLEVe1BCQ";
    private static final String bucket = "shop";
    private static final String url = "http://ozl8de5fg.bkt.clouddn.com/";

    public String upload(InputStream inputStream,String key){
        Configuration cfg = new Configuration(Zone.zone1());
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(inputStream,key,upToken,null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            return url + putRet.hash;
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            return null;
        }
    }
    public UEditorPut uploadUeditor(InputStream inputStream,String key){
        Configuration cfg = new Configuration(Zone.zone1());
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(accessKey, secretKey);
        StringMap putPolicy = new StringMap();
        putPolicy.put("returnBody", "{\"key\":\"$(key)\",\"name\":\"$(fname)\",\"mimeType\":\"$(mimeType)\",\"hash\":\"$(etag)\",\"bucket\":\"$(bucket)\",\"fsize\":$(fsize)}");
        putPolicy.put("callbackBodyType", "application/json");
        long expireSeconds = 3600;
        String upToken = auth.uploadToken(bucket, null, expireSeconds, putPolicy);
        try {
            Response response = uploadManager.put(inputStream,key,upToken,null, null);
            UEditorPut uEditorPut = response.jsonToObject(UEditorPut.class);
            uEditorPut.setUrl(url + uEditorPut.getKey());
            //解析上传成功的结果
            return uEditorPut;
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            return null;
        }
    }
}
